package com.example.esaclient;

import java.util.Calendar;
import java.util.Date;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;



public class TimelineActivity extends Activity {

	// Shared Preferences
	private static SharedPreferences mSharedPreferences;
	static final String PREF_ESA_USRID = "esa_userID";
	static  long LAST_UPDATE;
   public TabUserTimeline usrTimelineFragment;
   public TabMentionTimeline mentionTimelineFragment;
   
	public Integer usrID=0;
	public String[] servicesOn;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.timeline);		

		  final ActionBar ab = getActionBar();
          ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
          
          ab.setHomeButtonEnabled(true);
          ab.setDisplayHomeAsUpEnabled(true);
          
          ab.addTab(ab.newTab().setText("Home Timeline").setTabListener(new TabUserListener(new TabUserTimeline())));
          ab.addTab(ab.newTab().setText("Mention Timeline").setTabListener(new TabMentionListener(new TabMentionTimeline())));
          
		
        //getting usrID from shared Prefs
      	mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
		usrID = mSharedPreferences.getInt(PREF_ESA_USRID, 0);
          
		Log.w("ESA", "Calling GetDataUser...");		 
		new GetDataUser(this).execute(usrID.toString());
		Log.w("ESA", "Calling GetServiceOn...");
		new GetServiceOn(this).execute(usrID.toString());
		
		updateDB();
		
	}

	public void updateDB(){
		long u= mSharedPreferences.getLong(GlobalSettings.PREF_KEY_LAST_SRV_UPDATE, 0);
		long now =System.currentTimeMillis();
		if(Math.abs(u-now)>900000){ //if last update was before 15 minutes ago 
			Log.w("ESA", "Calling UpdatePostsDB...");
			new UpdatePostsDB(this).execute(usrID.toString()); 
		}
	}
    
	
	public void GetDataUserResult(String result){
		Log.w("ESA", "Exiting GetDataUser...");		 
		TextView tvResult; tvResult = (TextView)findViewById(R.id.txtWelcomeUsr);
		 tvResult.setText("Welcome "  +result);
	}
	
	public void GetServiceOnResult(String[] result) {
		Log.w("ESA", "Exiting GetServiceOn...");
		servicesOn=result; 
		Editor e = mSharedPreferences.edit();

		for(int i =0; i<result.length;i++){
			if( result[i] != null){
				try{
			String [] s = result[i].split("\\+\\-\\+");  //[0]->Socail [1]->Token [2]->username
			if (s[0].equals("Facebook"))  // Facebook
			{
			e.putBoolean(GlobalSettings.PREF_KEY_FACEBOOK_LOGIN, true);
			e.putString(GlobalSettings.PREF_FACEBOOK_TOKEN, s[1]);
			e.putString(GlobalSettings.PREF_KEY_FACEBOOK_USERNAME, s[2]);	
		}
			else if (s[0].equals("Twitter")) {
				e.putBoolean(GlobalSettings.PREF_KEY_TWITTER_LOGIN, true);
				e.putString(GlobalSettings.PREF_TWITTER_TOKEN, s[1]);
				e.putString(GlobalSettings.PREF_KEY_TWITTER_USERNAME, s[2]);	
			}
				}
				catch(RuntimeException ex){
					
					 ex.printStackTrace();
				}
		}
		}
		
	
		e.commit();
	}
	
	public void UpdateDbResult(Boolean result){
		Log.w("ESA", "Exiting UpdatePostsDB...");
		LAST_UPDATE= System.currentTimeMillis();
		Editor e = mSharedPreferences.edit();
		e.putLong(GlobalSettings.PREF_KEY_LAST_SRV_UPDATE, LAST_UPDATE);
		e.commit();
		//gestire eventuali errori di aggiornamento DB
	}
	
	/*******ACTION MENU SECTION*************/
	 
	  @Override
      public boolean onOptionsItemSelected(MenuItem item) {
          switch (item.getItemId()) {
              case R.id.mnuAddSocial:
                      Intent intent = new Intent(this, AddSocialActivity.class);
                      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                      startActivity(intent);
                      return true;
              case R.id.mnuRefresh:
            	   if(usrTimelineFragment.isVisible())
           	    	usrTimelineFragment.refresh();
            	   if(mentionTimelineFragment.isVisible())
            		   mentionTimelineFragment.refresh();
                  return true;
              case R.id.mnuSearch:
            	  Intent searchIntent = new Intent(this, SearchActivity.class);
            	  searchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                  startActivity(searchIntent);
                 return true;
              case R.id.mnuPost:
            	  Intent postIntent = new Intent(this, CrossPostActivity.class);
            	  postIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                  startActivity(postIntent);
                 return true;
              case R.id.mnuInsights:
            	  Intent insightsIntent = new Intent(this, InsightsActivity.class);
            	  insightsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                  startActivity(insightsIntent);
                 return true;
              default:
                  return super.onOptionsItemSelected(item);
          }
      }
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.timeline, menu);
		return true;
		
		
	}

// User Tab Listener
	 public class TabUserListener implements ActionBar.TabListener {
	      
	        public TabUserListener(TabUserTimeline fragment) {
	                usrTimelineFragment = fragment;
	        }

	        public void onTabSelected(Tab tab, FragmentTransaction ft) {
	               ft.add(R.id.flFragmentContent, usrTimelineFragment, "New Tab");
	        }

	        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
	                ft.remove(usrTimelineFragment);
	        }

	        public void onTabReselected(Tab tab, FragmentTransaction ft) {
	                // Toast.makeText(TabsActivity.this, "Reselected", Toast.LENGTH_SHORT).show();
	        }

	}
	 
	 
	 // Mention Tab Listener
	    public class TabMentionListener implements ActionBar.TabListener {
	       

	        public TabMentionListener(TabMentionTimeline fragment) {
	                mentionTimelineFragment = fragment;
	        }

	        public void onTabSelected(Tab tab, FragmentTransaction ft) {
	               ft.add(R.id.flFragmentContent, mentionTimelineFragment, "New Tab");
	        }

	        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
	                ft.remove(mentionTimelineFragment);
	        }

	        public void onTabReselected(Tab tab, FragmentTransaction ft) {
	                // Toast.makeText(TabsActivity.this, "Reselected", Toast.LENGTH_SHORT).show();
	        }

	}


	    
	    @Override
	    protected void onRestart() {
	    updateDB();
	    super.onRestart();
	    if(usrTimelineFragment.isVisible())
	    	usrTimelineFragment.refresh();
	    if( mentionTimelineFragment.isVisible())
	    	mentionTimelineFragment.refresh();
	    }

	    
	    @Override
	    public void onBackPressed() {
	        exitPrompt();

	    }
	    

private void exitUser(){
	// Clear the shared preferences
	 Editor e = mSharedPreferences.edit();
     e.remove(GlobalSettings.PREF_ESA_USRID);
     
     e.remove(GlobalSettings.PREF_KEY_TWITTER_LOGIN);
     e.remove(GlobalSettings.PREF_KEY_TWITTER_USERNAME);
     
     e.remove(GlobalSettings.PREF_KEY_FACEBOOK_LOGIN);
     e.remove(GlobalSettings.PREF_KEY_FACEBOOK_USERNAME);
     
     e.remove(GlobalSettings.PREF_KEY_GOOGLE_LOGIN);
     e.remove(GlobalSettings.PREF_KEY_GOOGLE_USERNAME );
     
     e.commit();
	
    finish();

}
private void exitPrompt(){
    new AlertDialog.Builder(this)
    .setIcon(android.R.drawable.ic_dialog_alert)
    .setTitle("Log out")
    .setMessage("Are you sure you want to log out?")
    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {   
        @Override
        public void onClick(DialogInterface dialog, int which) {            
            exitUser();
        }
    })
    .setNeutralButton("Exit but don't logout",  new DialogInterface.OnClickListener() {   
        @Override
        public void onClick(DialogInterface dialog, int which) {            
           finish();
        }
    })
    .setNegativeButton("No", null)
    .show();
}
	    
}


